import Vue from 'vue';
import Router from 'vue-router';
import { Message } from 'element-ui';
import Home from '@/views/home';
import store from '@/vuex';
import { getToken } from '@/utils/auth';
import whiteList from './white';
import routeConfig from './config';

Vue.use(Router);

const { misConfig, proConfig, purConfig, invConfig, traConfig, manConfig, conConfig } = routeConfig;
// const { misConfig, purConfig, invConfig, manConfig, conConfig } = routeConfig;

// 大模块
const Mission = () => import('@/views/mission');
const Product = () => import('@/views/product');
const Purchase = () => import('@/views/purchase');
const Inventory = () => import('@/views/inventory');
const Train = () => import('@/views/train');
const Manage = () => import('@/views/manage');
const Config = () => import('@/views/config');

export const constantRouterMap = [{
  path: '/login',
  component: () => import('@/views/login'),
}, {
  path: '/404',
  component: () => import('@/views/404'),
}];

export const asyncRouterMap = [{
  path: '*',
  redirect: '/404',
  hidden: true
}];

export const homeRouterMap = [{
  path: '/mission',
  name: 'mission',
  value: '任务',
  hidden: false,
  icon: 'tickets',
  component: Mission,
  redirect: '/mission/approve',
  children: misConfig
}, {
  path: '/product',
  name: 'product',
  value: '产品',
  hidden: false,
  icon: 'goods',
  component: Product,
  redirect: '/product/need',
  children: proConfig
}, {
  path: '/purchase',
  name: 'purchase',
  value: '采购',
  hidden: false,
  icon: 'star-on',
  redirect: '/purchase/plan',
  component: Purchase,
  children: purConfig
}, {
  path: '/inventory',
  name: 'inventory',
  value: '库存',
  hidden: false,
  icon: 'share',
  component: Inventory,
  redirect: '/inventory/overview',
  children: invConfig
}, {
  path: '/manage',
  name: 'manage',
  value: '管理',
  hidden: false,
  icon: 'setting',
  component: Manage,
  redirect: '/manage/staff',
  children: manConfig
}, {
  path: '/train',
  name: 'train',
  value: '培训',
  hidden: false,
  icon: 'news',
  component: Train,
  redirect: '/train/course',
  children: traConfig
}, {
  path: '/config',
  name: 'config',
  value: '配置',
  hidden: false,
  icon: 'menu',
  component: Config,
  redirect: '/config/data',
  children: conConfig
}];

const router = new Router({ routes: constantRouterMap });

router.beforeEach((to, from, next) => {
  // 判断是否有token
  const token = getToken();
  if (store.getters.token || token) {
    // 刷新页面处理
    if (!store.getters.token) {
      store.dispatch('setToken', token);
    }
    if (to.path === '/login') {
      next('/');
    } else {
      // 判断当前用户是否已拉取完user_info信息
      if (store.getters.roles.length === 0) {
        // 拉取user_info
        store.dispatch('getUserInfo').then((res) => {
          const roles = res.roles;
          store.dispatch('generateRoutes', { roles }).then(({ homeRouters, asyncRouters }) => {
            // 动态添加可访问路由表
            if (homeRouters.length) {
              const homeRoutes = [{
                path: '/',
                name: 'home',
                component: Home,
                redirect: homeRouters[0].path,
                children: homeRouters
              }];
              router.addRoutes(homeRoutes);
              router.addRoutes(asyncRouters);
              // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
              next({ ...to, replace: true });
            } else {
              store.dispatch('goLogout').then(() => {
                Message.info('该用户无可访问内容，请用管理员赋予权限');
                next({ path: '/login', replace: true });
              });
            }
          }).catch(() => {
            next('/404');
          });
        });
      } else {
        // 当有用户权限的时候，说明所有可访问路由已生成 如访问没权限的页面会自动进入404页面
        next();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else if (to.path === '/login') {
      next();
    } else {
      // 否则全部重定向到登录页
      next('/login');
    }
  }
});

export default router;
